import useEventListener from '@/hooks/event/useEventListener';
import type { RemoveEventFn } from '@/hooks/event/useEventListener';
import type { Ref } from 'vue';

const useDomReachBottom = (elRef: Ref<Element | null>, limitDistance: number = 0): Ref<boolean> => {
  let removeEventFn: RemoveEventFn | null = null;
  const isReachBottom = ref<boolean>(false);

  const onElementScroll = () => {
    const scrollHeight = elRef.value!.scrollHeight;
    const scrollTop = elRef.value!.scrollTop;
    const clientHeight = (elRef.value! as HTMLElement).clientHeight;
    if (scrollTop + limitDistance + clientHeight >= scrollHeight) {
      console.log('触底~');
      isReachBottom.value = true;
    }
  };

  watch(
    elRef,
    (v) => {
      if (!!v) {
        const { removeEvent } = useEventListener({
          el: v,
          eventName: 'scroll',
          listener: onElementScroll,
          wait: 300,
        });
        removeEventFn = removeEvent;
      }
    },
    { immediate: true }
  );

  onBeforeUnmount(() => removeEventFn && removeEventFn());

  return isReachBottom;
};

export default useDomReachBottom;
